﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections.Specialized;
using RepositoriesInterfaces;
using Subfaculty.Controllers;
using Entities;

namespace Subfaculty.ViewModels.Binders
{
    public class AllocationCreateBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            AllocationController controllerHandler = (AllocationController)controllerContext.Controller;
            AllocationCreateViewModel model = new AllocationCreateViewModel();
            IList<StudyPlanItem> SPItemList = new List<StudyPlanItem>();
            IList<Group> GroupList = new List<Group>();
            NameValueCollection coll = controllerContext.HttpContext.Request.Form;
            IList<String> keysArray = coll.AllKeys;

            model.RatingFactor = Convert.ToDouble(controllerContext.HttpContext.Request["RatingFactor"]);
            model.FactorForControl = Convert.ToDouble(controllerContext.HttpContext.Request["FactorForControl"]);
            model.FactorForConsultation = Convert.ToDouble(controllerContext.HttpContext.Request["FactorForConsultation"]);
            model.FactorForBeforeExamConsultation = Convert.ToDouble(controllerContext.HttpContext.Request["FactorForBeforeExamConsultation"]);
            model.typeLabSplitting = controllerContext.HttpContext.Request["radioLab"];
            model.typePracticeSplitting = controllerContext.HttpContext.Request["radioPractice"];
            model.StudyPlanItems = new List<StudyPlanItem>();
            model.Groups = new List<Group>();
            

            foreach (String key in keysArray)
            {
                if (key.StartsWith("spi_"))
                {
                    model.StudyPlanItems.Add(controllerHandler.PlanItemRepository.GetByID(Convert.ToInt32(coll[key])));
                }
                else if (key.StartsWith("group_"))
                {
                    model.Groups.Add(controllerHandler.GroupRepository.GetByID(Convert.ToInt32(coll[key])));
                }
            }

            return model;
        }
    }
}